package com.example.demo.shell;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class ShellUtil {

	private static JSch jsch = new JSch();
	
	public static ShellResult exec(String command, String host, String username, String password) {
		ShellResult result = new ShellResult();
		Session session = null;
		ChannelExec channel = null;
		try {
			session = jsch.getSession(username, host, AgentConstant.port);
			session.setUserInfo(new ShellUserInfo(password) {});
			session.connect(10000);
			
			channel = (ChannelExec) session.openChannel("exec");
			channel.setCommand(command);
			ByteArrayOutputStream errout = new ByteArrayOutputStream();
			channel.setErrStream(errout);
			channel.setInputStream(null);
			InputStream in = channel.getInputStream();
			channel.connect();
			
			byte[] b = new byte[1024];
			StringBuilder sb = new StringBuilder();
			int len = 0;
			while(true) {
				while(in.available() > 0) {
					len = in.read(b);
					sb.append(new String(b, 0, len));
				}
				if(channel.isClosed()) {
					result.setStdout(sb.toString());
					result.setState(channel.getExitStatus());
					if(channel.getExitStatus() != 0) {
						result.setErrout(new String(errout.toByteArray()));
					}
					break;
				}
			}
		} catch (JSchException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(channel != null)
				channel.disconnect();
			if(session != null)
				session.disconnect();
		}
		
		return result;
	}
	
	public static String packageCmd(String command) {
		
		return command;
	}
}
